package cn.com.note.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;

import cn.com.note.R;
import cn.com.note.activity.VersionUpdate;
import cn.com.note.service.UpdateIntentService;
import cn.com.note.view.DownloadProgressButton;
import rx.Observable;
import rx.Subscription;


public class DownloadDialog extends Dialog {
    private TextView tvTitle;
    private TextView tvDesc;
    private ImageView imgCancle;
    private Context context;
    DownloadProgressButton downloadButton;
    Button resetButton;
    private Subscription sub;
    private Observable<Long> obser;
    DLClickListener listener;


    public interface DLClickListener {
        void onStart();

        void onFinish();

        void onCancel();
    }
   UpdateBroadcast receiver;

    private void initBroadcastReceiver() {
        //创建广播接受者对象
        receiver = new UpdateBroadcast();
        //注册广播接受者java代码
        IntentFilter intentFilter = new IntentFilter(UpdateIntentService.UPDATE_APK);
        intentFilter.addAction(UpdateIntentService.UPDATE_APK_ERROR);
        //注册receiver
        context.registerReceiver(receiver, intentFilter);
    }

    public void unReceiver(Context c){
        c.unregisterReceiver(receiver);
    }

    public void setDLClickListener(DLClickListener listener) {
        this.listener = listener;
    }

    public DownloadDialog(Context context) {
        super(context, R.style.ios_bottom_dialog);
        this.context = context;
        init();
        initBroadcastReceiver();
    }

    private void init() {
        View contentView = LayoutInflater.from(context).inflate(R.layout.dialog_download, null);
        tvTitle = (TextView) contentView.findViewById(R.id.tv_title);
        tvDesc = (TextView) contentView.findViewById(R.id.tv_update_desc);
        imgCancle = (ImageView) contentView.findViewById(R.id.img_cancle);
        downloadButton = (DownloadProgressButton) contentView.findViewById(R.id.download);
        resetButton = (Button) contentView.findViewById(R.id.rest);
        downloadButton.setEnablePause(false);
        imgCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (downloadButton != null &&
                        downloadButton.getState() == DownloadProgressButton.DOWNLOADING) {
                    //正在下载

                } else {
                    dismiss();
                    if (listener != null) {
                        listener.onCancel();
                    }
                }
            }
        });
        setContentView(contentView);
        setCancelable(false);
        setCanceledOnTouchOutside(false);
        setWindow();
        downloadButton.setOnDownLoadClickListener(new DownloadProgressButton.OnDLClickListener() {
            @Override
            public void clickDownload() {
                if (listener != null) {
                    listener.onStart();
                }
            }

            @Override
            public void clickPause() {
            }

            @Override
            public void clickResume() {
            }

            @Override
            public void clickFinish() {
                if (listener != null) {
                    listener.onFinish();
                }
            }
        });
    }

    /**
     * 获取当前的下载状态
     *
     * @return
     */
    public int getState() {
        return downloadButton.getState();
    }

    /**
     * 重置状态
     */
    public void stateRest() {
        if (downloadButton != null) {
            downloadButton.reset();
        }
    }

    /**
     * 设置标题标题
     *
     * @param title
     * @return
     */
    public DownloadDialog setTitle(String title) {
        tvTitle.setText(title);
        return this;
    }

    /**
     * 设置 版本更新内容文案
     *
     * @param desc
     * @return
     */
    public DownloadDialog setDesc(String desc) {
        tvDesc.setText(desc);
        return this;
    }

    /**
     * 更新 下载进度
     *
     * @param progress
     */
    public void upgradeProgress(int progress) {
        if (progress < 0) {
            progress = 0;
        } else if (progress > 100) {
            progress = 100;
        }
        downloadButton.setProgress(progress);
    }

    private void setWindow() {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.width = (int) (ScreenUtils.getScreenWidth() * 0.85);
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.alpha = 1.0f;
        getWindow().setWindowAnimations(R.style.menu_anim_style);
        getWindow().setAttributes(layoutParams);
    }


    @Override
    public void show() {
        if (isValidContext()) {
            super.show();
        }
    }

    @Override
    public void dismiss() {
        if (isValidContext()) {
            super.dismiss();
            if (listener != null) {
                listener.onCancel();
            }
        }
    }
    class UpdateBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == UpdateIntentService.UPDATE_APK) {
                int progress = intent.getIntExtra("progress", 0);
                upgradeProgress(progress);
            } else if (intent.getAction() == UpdateIntentService.UPDATE_APK_ERROR) {
                //更新失败
                boolean isFail = intent.getBooleanExtra("apk_error", false);
                boolean isFinish = intent.getBooleanExtra("apk_finish", false);
                stateRest();
                if (isFinish) {
                    dismiss();
                }
                if (isFail) {
                    stateRest();
                    ToastUtils.showShort("文件下载失败,请重新下载！");
                }
            }
        }
    }
    private boolean isValidContext() {
        try {
            Activity activity = (Activity) context;
            if (Build.VERSION.SDK_INT >= 17) {
                return !activity.isDestroyed() && !activity.isFinishing();
            }
            return !activity.isFinishing();
        } catch (Exception e) {
            return false;
        }
    }
}